package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class VoiceService {

    // 导入fastdfs服务
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VoiceApi voiceApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public ResponseEntity<Object> uploadVoice(MultipartFile soundFile) throws IOException {
        // 1.新建声音对象
        Voice voice = new Voice();

        // 2.设置相关信息
        voice.setUserId(UserHolder.getUserId());
        voice.setCreated(System.currentTimeMillis());

        // 3.上传语音文件到fastdfs
        if(soundFile!=null){
            // 文件名
            String filename = soundFile.getOriginalFilename();
            // 扩展名
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),extName,null);

            // 获取语音存储的完整url
            String voiceUrl=fdfsWebServer.getWebServerUrl()+ storePath.getFullPath();

            voice.setVoiceUrl(voiceUrl);
        }

        // 4.调用api保存对象数据
        voice.setId(ObjectId.get());    // 手动设置id

        voiceApi.save(voice);

        // 5.返回空
        return ResponseEntity.ok(null);
    }

    public ResponseEntity<Object> findOne() throws ParseException {
        // 获取当前用户id
        Long userId = UserHolder.getUserId();

        // 随便找一条语音,这条语音发布者不能是自己
        Voice one = voiceApi.findOne(userId);

        // 封装为vo类型
        VoiceVo voiceVo = new VoiceVo();


        Long id = one.getUserId();
        UserInfo userInfo = userInfoApi.findById(id);

        // 封装vo
        voiceVo.setId(id);
        voiceVo.setAvatar(userInfo.getAvatar());
        voiceVo.setNickname(userInfo.getNickname());
        voiceVo.setGender(userInfo.getGender());
        voiceVo.setAge(userInfo.getAge());
        voiceVo.setSoundUrl(one.getVoiceUrl());

        // 使用redis，在执行接收语音的时候新建实体类，用来记录用户及其当日限定次数
        String key = "Remaining_Times_Of_"+userId;
        String times = redisTemplate.opsForValue().get(key);

        // 获取当前时间，年月日
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String tk = sdf.format(date); // 转为年月日

        Date now = sdf.parse(tk);

        String timeKey = "Today_"+userId;

        if (times==null){
            // 如果是空的，说明该用户今天还没接过
            // 由于是频繁修改的操作，所以不适宜用redis,用mongo
            redisTemplate.opsForValue().set(key,"9");

            // 日期存入缓存
            redisTemplate.opsForValue().set(timeKey,tk);
        }else {
            Integer rtimes = Integer.parseInt(times) - 1;

            // 如果不是空的，肯定有timekey,获取年月日
            String s = redisTemplate.opsForValue().get(timeKey);
            // 转化为日期
            Date parse = sdf.parse(s);
            // 与今日比较
            if(now.after(parse)){
                // 如果是真的，设定次数为9
                rtimes=9;
                // 且把现在作为timeKey
                String format = sdf.format(now);
                redisTemplate.opsForValue().set(timeKey,format);
            }
            redisTemplate.opsForValue().set(key,rtimes.toString());
        }

        int rtimes = Integer.parseInt(redisTemplate.opsForValue().get(key));

        // 剩余次数调整
        voiceVo.setRemainingTimes(rtimes);
        if(voiceVo.getRemainingTimes()<=0){
            return ResponseEntity.status(500).body("次数用完啦！");
        }

        // 返回
        return ResponseEntity.ok(voiceVo);
    }
}
